package com.zhanghe.study.netty.codec;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.ReferenceCountUtil;

/**
 * 服务端处理器
 * @author zh
 * @date 2020/12/2 11:33
 */
// 继承ChannelInboundHandlerAdapter
public class ServerHandler extends ChannelInboundHandlerAdapter {

    // 读取客户端发送的数据
    // ChannelHandlerContext 上下文对象，含有管道pipeline，通道channel，地址
    // Object 消息数据
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        try{
            UserProto.User user = (UserProto.User) msg;

            System.out.println("接收到的消息为：->"+user);

            // 回复客户端
//            ctx.writeAndFlush(Unpooled.copiedBuffer("888".getBytes()))
//                    // 数据发送完之后主动断开连接
//            .addListener(ChannelFutureListener.CLOSE);
        } finally {
            // 释放缓冲
            ReferenceCountUtil.release(msg);
        }
    }

    // 处理异常
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        // 关闭
        ctx.close();
    }

    // 数据读取完毕
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        // 回复客户端
        ctx.writeAndFlush(Unpooled.copiedBuffer("hello".getBytes()));

    }
}
